<template>
	<view class="weather-container">
		<view v-if="weatherData" class="weather-info">
			<h1>泉州</h1>
			<view>日期：{{ tomorrowDate }}</view>
			<view>星期：{{ tomorrowWeek }}</view>
			<view>最高温：{{ tomorrowMaxTemp }}°C</view>
			<view>最低温：{{ tomorrowMinTemp }}°C</view>
		</view>
		<view v-else>加载中...</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				weatherData: null
			}
		},
		// 组件创建时立即触发（子组件导入时也会执行，替代页面级的onLoad）
		created() {
			console.log('天气组件创建，开始请求数据');
			this.getWeather();
		},
		computed: {
			tomorrowDate() {
				return this.weatherData?.data?.forecast[1]?.date || '';
			},
			tomorrowWeek() {
				return this.weatherData?.data?.forecast[1]?.week || '';
			},
			tomorrowMaxTemp() {
				// 处理接口返回格式（可能包含"高温"文字，提取数字）
				return this.weatherData?.data?.forecast[1]?.high?.replace('高温', '') || '';
			},
			tomorrowMinTemp() {
				// 处理接口返回格式（可能包含"低温"文字，提取数字）
				return this.weatherData?.data?.forecast[1]?.low?.replace('低温', '') || '';
			}
		},
		methods: {
			getWeather() {
				uni.request({
					// 注意：H5端需配合manifest.json的代理配置，否则跨域
					// 代理配置后可改为：url: '/weatherApi/api/weather/city/101230501',
					url: 'http://t.weather.sojson.com/api/weather/city/101230501',
					method: 'GET',
					success: (res) => {
						console.log('天气请求成功', res.data);
						// 仅当接口返回成功时赋值（避免无效数据）
						if (res.statusCode === 200 && res.data?.data) {
							this.weatherData = res.data;
						} else {
							console.warn('接口返回数据格式异常', res);
						}
					},
					fail: (err) => {
						console.error('天气请求失败（详细信息）', err);
					},
					complete: () => {
						console.log('天气请求完成，当前数据：', this.weatherData);
					}
				});
			}
		}
	}
</script>

<style scoped>
/* 加scoped避免样式污染其他组件 */
.weather-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	justify-content: center;
	height: 100vh;
	font-size: 2rem;
	font-weight: bold;
	color: white;
	padding: 10rpx;
	text-shadow: 2px 2px 2px black;
}

/* 避免body样式污染全局（组件中尽量不用body选择器） */
.weather-container::before {
	content: '';
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-image: url(/static/background/chenglong.jpg);
	background-repeat: no-repeat;
	background-position: center;
	background-attachment: fixed;
	background-size: cover;
	z-index: -1;
}

.weather-info {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.weather-info h1 {
	margin: 0;
	font-size: 2.5rem;
}
</style>